package org.cjlm.ui.bill;

import com.formdev.flatlaf.util.StringUtils;
import org.cjlm.MLocator;
import org.cjlm.itf.CompDAO;
import org.cjlm.ui.pub.MInternalFrame;
import org.cjlm.vo.comp.AttributeVO;
import org.cjlm.vo.comp.CompVO;
import org.cjlm.vo.comp.EntityVO;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import java.util.Vector;

public class EntityDesignerFrm extends MInternalFrame {
    // 组件声明
    private JTable compTable, entityTable, fieldTable;
    private DefaultTableModel compTableModel, entityTableModel, fieldTableModel;
    private static final CompDAO compDao = MLocator.getInstance(CompDAO.class);
    private String selectedCompId;
    private String selectedEntityId;

    public EntityDesignerFrm(String title, boolean max, int width, int height) {
        super(title, max, width, height);
        initUI();
    }
    private void initUI() {
        // 主面板布局
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10,  10, 10, 10));

        // 工具栏设置
        JToolBar toolBar = createToolBar();
        JSplitPane mainSplitPane = createMainSplitPane();

        // 事件绑定
        bindButtonActions(toolBar);

        // 组装界面
        mainPanel.add(toolBar,  BorderLayout.NORTH);
        mainPanel.add(mainSplitPane,  BorderLayout.CENTER);
        getContentPane().add(mainPanel);

        // 数据加载
        loadData();
        addTableSelectionListeners();
        addDoubleClickListeners();
        addRightClickMenu();
    }

    private JToolBar createToolBar() {
        JToolBar toolBar = new JToolBar();
        toolBar.setFloatable(false);
        toolBar.setLayout(new  FlowLayout(FlowLayout.LEFT, 10, 5));

        String[] buttonTypes = {"comp", "entity", "field"};
        for (String type : buttonTypes) {
            String label = switch (type) {
                case "comp" -> "创建业务组件";
                case "entity" -> "创建实体";
                default -> "创建字段";
            };
            toolBar.add(createToolbarButton(label,  type));
        }
        return toolBar;
    }

    private JSplitPane createMainSplitPane() {
        JSplitPane mainSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
        mainSplitPane.setResizeWeight(0.3);
        mainSplitPane.setDividerLocation(0.3);

        // 左侧组件面板
        compTableModel = createTableModel(new String[]{"id", "业务组件编码", "业务组件名称"});
        compTable = createStyledTable(compTableModel);
        hideTableColumns(compTable, "id");
        JScrollPane compScrollPane = wrapInScrollPane(compTable, "业务组件列表");

        // 中间实体面板
        entityTableModel = createTableModel(new String[]{"id","compid","实体编码","实体名称","是否主实体","是否档案","实体类","物理表"});
        entityTable = createStyledTable(entityTableModel);
        hideTableColumns(entityTable, "id", "compid");
        JScrollPane entityScrollPane = wrapInScrollPane(entityTable, "实体列表");

        // 右侧字段面板
        fieldTableModel = createTableModel(new String[]{"id","compid","entityid","parentcode","是否主键","字段编码","字段名称","字段类型","数据类型","字段长度","字段精度","参照类型","枚举类型"});
        fieldTable = createStyledTable(fieldTableModel);
        hideTableColumns(fieldTable, "id", "compid", "entityid", "parentcode");
        JScrollPane fieldScrollPane = wrapInScrollPane(fieldTable, "字段列表");

        // 组装分割面板
        JSplitPane verticalSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        verticalSplitPane.setResizeWeight(0.5);
        verticalSplitPane.setTopComponent(entityScrollPane);
        verticalSplitPane.setBottomComponent(fieldScrollPane);
        verticalSplitPane.setDividerSize(5);

        mainSplitPane.setLeftComponent(compScrollPane);
        mainSplitPane.setRightComponent(verticalSplitPane);
        SwingUtilities.invokeLater(() -> {
            mainSplitPane.setDividerLocation(0.25); // 设置初始位置为 25%
        });
        return mainSplitPane;
    }

    private DefaultTableModel createTableModel(String[] columnNames) {
        return new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
    }

    private void hideTableColumns(JTable table, String... columnIds) {
        for (String colId : columnIds) {
            TableColumn column = table.getColumn(colId);
            if (column != null) table.removeColumn(column);
        }
    }

    private JScrollPane wrapInScrollPane(JTable table, String title) {
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setBorder(createTitledBorder(title));
        return scrollPane;
    }

    private void bindButtonActions(JToolBar toolBar) {
        for (Component comp : toolBar.getComponents())  {
            if (comp instanceof JButton button) {
                String cmd = button.getActionCommand();
                button.addActionListener(e  -> {
                    switch (cmd) {
                        case "comp" -> openCreateCompDialog(e);
                        case "entity" -> openCreateEntityDialog(e);
                        case "field" -> openCreateFieldDialog(e);
                    }
                });
            }
        }
    }

    private void addRightClickMenu() {
        String[] tableTypes = {"comp", "entity", "field"};
        JTable[] tables = {compTable, entityTable, fieldTable};

        for (int i = 0; i < tables.length;  i++) {
            JPopupMenu popup = createTablePopupMenu(tableTypes[i]);
            tables[i].setComponentPopupMenu(popup);
            int finalI = i;
            tables[i].addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    showPopup(e, tables[finalI], popup);
                }
                @Override
                public void mouseReleased(MouseEvent e) {
                    showPopup(e, tables[finalI], popup);
                }
            });
        }
    }

    private void handleDeleteOperation(String tableType) {
        switch (tableType) {
            case "comp" -> deleteSelectedItem(
                    compTable, compTableModel,
                    "业务组件", "确定删除该业务组件及其所有关联数据？"
            );
            case "entity" -> deleteSelectedItem(
                    entityTable, entityTableModel,
                    "实体", "确定删除该实体及其所有字段？"
            );
            case "field" -> deleteSelectedItem(
                    fieldTable, fieldTableModel,
                    "字段", "确定删除该字段？"
            );
        }
    }

    private void deleteSelectedItem(JTable table, DefaultTableModel model, String itemType, String confirmMsg) {
        int row = table.getSelectedRow();
        if (row == -1) return;

        String id = model.getValueAt(row,  0).toString();
        int confirm = JOptionPane.showConfirmDialog(
                this, confirmMsg, "确认删除", JOptionPane.YES_NO_OPTION
        );

        if (confirm == JOptionPane.YES_OPTION) {
            try {
                deleteFromDatabase(itemType, id);
                refreshAfterDelete(itemType);
            } catch (Exception ex) {
                showErrorDialog("删除" + itemType + "失败", ex);
            }
        }
    }

    private void deleteFromDatabase(String itemType, String id) throws Exception {
        switch (itemType) {
            case "业务组件" -> {
                CompVO compVO = new CompVO();
                compVO.setPrimaryKeyValue(id);
                compDao.delete(compVO);
            }
            case "实体" -> {
                EntityVO entityVO = new EntityVO();
                entityVO.setPrimaryKeyValue(id);
                compDao.delete(entityVO);
            }
            case "字段" -> {
                AttributeVO fieldVO = new AttributeVO();
                fieldVO.setPrimaryKeyValue(id);
                compDao.delete(fieldVO);
            }
        }
    }

    private void refreshAfterDelete(String itemType) {
        switch (itemType) {
            case "业务组件" -> {
                refreshCompTable();
                entityTableModel.setRowCount(0);
                fieldTableModel.setRowCount(0);
                selectedCompId = null;
                selectedEntityId = null;
            }
            case "实体" -> {
                refreshEntityTable(selectedCompId);
                fieldTableModel.setRowCount(0);
                selectedEntityId = null;
            }
            case "字段" -> refreshFieldTable(selectedCompId, selectedEntityId);
        }
    }

    private JPopupMenu createTablePopupMenu(String tableType) {
        JPopupMenu popup = new JPopupMenu();
        JMenuItem deleteItem = new JMenuItem("删除");
        deleteItem.addActionListener(e -> {
            handleDeleteOperation(tableType);
        });

        popup.add(deleteItem);
        return popup;
    }

    private void showPopup(MouseEvent e, JTable table, JPopupMenu popup) {
        if (e.isPopupTrigger())  {
            int row = table.rowAtPoint(e.getPoint());
            if (row >= 0) {
                table.setRowSelectionInterval(row,  row);
                popup.show(e.getComponent(),  e.getX(),  e.getY());
            }
        }
    }

    private void showErrorDialog(String title, Exception ex) {
        JOptionPane.showMessageDialog(this,
                title + ": " + ex.getMessage(),
                "错误",
                JOptionPane.ERROR_MESSAGE);
    }

    // 新增方法：添加表格选择监听
    private void addTableSelectionListeners() {
        compTable.getSelectionModel().addListSelectionListener(e  -> {
            if (!e.getValueIsAdjusting()  && compTable.getSelectedRow()  != -1) {
                int selectedRow = compTable.getSelectedRow();
                selectedCompId = compTableModel.getValueAt(selectedRow,  0).toString();
                loadEntityData(selectedCompId);
            }
        });

        entityTable.getSelectionModel().addListSelectionListener(e  -> {
            if (!e.getValueIsAdjusting()  && entityTable.getSelectedRow()  != -1) {
                int selectedRow = entityTable.getSelectedRow();
                selectedEntityId = entityTableModel.getValueAt(selectedRow,  0).toString();
//                loadFieldData(selectedCompId, selectedEntityId);
                refreshFieldTable(selectedCompId, selectedEntityId);
            }
        });
    }

    private void loadEntityData(String selectedCompId) {
        refreshEntityTable(selectedCompId);
        fieldTableModel.setRowCount(0);
    }

    // 新增方法：添加双击事件监听
    private void addDoubleClickListeners() {
        // 业务组件表格双击事件
        compTable.addMouseListener(new  MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount()  == 2 && e.getButton()  == MouseEvent.BUTTON1) {
                    int row = compTable.getSelectedRow();
                    if (row != -1) {
                        Vector<Object> rowData = new Vector<>();
                        for (int i = 0; i < compTableModel.getColumnCount();  i++) {
                            rowData.add(compTableModel.getValueAt(row,  i));
                        }
                        openEditCompDialog(rowData);
                    }
                }
            }
        });

        // 实体表格双击事件
        entityTable.addMouseListener(new  MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount()  == 2 && e.getButton()  == MouseEvent.BUTTON1) {
                    int row = entityTable.getSelectedRow();
                    if (row != -1) {
                        Vector<Object> rowData = new Vector<>();
                        for (int i = 0; i < entityTableModel.getColumnCount();  i++) {
                            rowData.add(entityTableModel.getValueAt(row,  i));
                        }
                        openEditEntityDialog(rowData);
                    }
                }
            }
        });

        // 字段表格双击事件
        fieldTable.addMouseListener(new  MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount()  == 2 && e.getButton()  == MouseEvent.BUTTON1) {
                    int row = fieldTable.getSelectedRow();
                    if (row != -1) {
                        Vector<Object> rowData = new Vector<>();
                        for (int i = 0; i < fieldTableModel.getColumnCount();  i++) {
                            rowData.add(fieldTableModel.getValueAt(row,  i));
                        }
                        openEditFieldDialog(rowData);
                    }
                }
            }
        });
    }

    // 新增方法：打开编辑业务组件对话框
    private void openEditCompDialog(Vector<Object> rowData) {
        CreateCompDialog dialog = new CreateCompDialog();
        dialog.setEditMode(true);
        dialog.setData(
                rowData.get(0).toString(),  // id
                rowData.get(1).toString(),  // code
                rowData.get(2).toString()   // name
        );

        dialog.addWindowListener(new  WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                refreshCompTable();
            }
        });
        dialog.setVisible(true);
    }

    // 新增方法：打开编辑实体对话框
    private void openEditEntityDialog(Vector<Object> rowData) {
        CreateEntityDialog dialog = new CreateEntityDialog();
        dialog.setEditMode(true);
        dialog.setData(
                rowData.get(0).toString(),  // id
                rowData.get(1).toString(),  // compid
                rowData.get(2).toString(),  // code
                rowData.get(3).toString(),  // name
                rowData.get(4).toString().equals("Y"),  // primary
                rowData.get(5).toString().equals("Y"),   // archive
                rowData.get(6).toString(),  //clazzname
                rowData.get(7).toString()  //dbname
        );

        dialog.addWindowListener(new  WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                refreshEntityTable(selectedCompId);
            }
        });
        dialog.setVisible(true);
    }

    // 新增方法：打开编辑字段对话框
    private void openEditFieldDialog(Vector<Object> rowData) {
        CreateFieldDialog dialog = new CreateFieldDialog();
        dialog.setEditMode(true);
        dialog.setData(
                rowData.get(0).toString(),  // id
                rowData.get(1).toString(),  // compid
                rowData.get(2).toString(),  // entityid
                rowData.get(3).toString(),  // parentcode
                rowData.get(4).toString().equals("Y"),  // primary
                rowData.get(5).toString(),  // code
                rowData.get(6).toString(),  // name
                rowData.get(7).toString(),  // type
                rowData.get(8).toString(),  // dbtype
                rowData.get(9) == null || rowData.get(9).toString().length() == 0 ? null : Integer.parseInt(rowData.get(9).toString()),  // dblength
                rowData.get(10) == null || rowData.get(10).toString().length() == 0 ? null : Integer.parseInt(rowData.get(10).toString()),  // dbjd
                rowData.get(11).toString(),  // doctype
                rowData.get(12).toString()   // enumtype
        );

        dialog.addWindowListener(new  WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                refreshFieldTable(selectedCompId, selectedEntityId);
            }
        });
        dialog.setVisible(true);
    }

    // 新增方法：刷新业务组件表格
    private void refreshCompTable() {
        compTableModel.setRowCount(0);
        try {
            List<CompVO> list = compDao.query(new  CompVO());
            if (list != null) {
                for (CompVO compVO : list) {
                    compTableModel.addRow(new  Object[]{
                            compVO.getId(),
                            compVO.getCode(),
                            compVO.getName()
                    });
                }
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this,
                    "加载业务组件失败: " + e.getMessage(),
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
        }
    }

    // 新增方法：刷新实体表格
    private void refreshEntityTable(String compId) {
        entityTableModel.setRowCount(0);
        if (compId != null && !compId.isEmpty())  {
            try {
                EntityVO entityVO = new EntityVO();
                entityVO.setCompId(compId);
                List<EntityVO> list = compDao.query(entityVO);
                if (list != null) {
                    for (EntityVO vo : list) {
                        entityTableModel.addRow(new  Object[]{
                                vo.getId(),
                                vo.getCompId(),
                                vo.getCode(),
                                vo.getName(),
                                vo.getIsMain(),
                                vo.getIsDoc(),
                                vo.getClazzname(),
                                vo.getDbname()
                        });
                    }
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this,
                        "加载实体失败: " + e.getMessage(),
                        "错误",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    // 新增方法：刷新字段表格
    private void refreshFieldTable(String compId, String entityId) {
        fieldTableModel.setRowCount(0);
        if (compId != null && !compId.isEmpty()  &&
                entityId != null && !entityId.isEmpty())  {

            try {
                AttributeVO fieldVO = new AttributeVO();
                fieldVO.setCompId(compId);
                fieldVO.setEntityId(entityId);
                List<AttributeVO> list = compDao.query(fieldVO);
                if (list != null) {
                    for (AttributeVO vo : list) {
                        fieldTableModel.addRow(new  Object[]{
                                vo.getId(),
                                vo.getCompId(),
                                vo.getEntityId(),
                                vo.getParentCode(),
                                vo.getIsPriKey(),
                                vo.getCode(),
                                vo.getName(),
                                vo.getType(),
                                vo.getDbtype(),
                                vo.getDblength(),
                                vo.getDbjd(),
                                vo.getDocCompId(),
                                vo.getEnmu()
                        });
                    }
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this,
                        "加载字段失败: " + e.getMessage(),
                        "错误",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    // 创建带样式的表格
    private JTable createStyledTable(DefaultTableModel model) {
        JTable table = new JTable(model);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.setRowHeight(30);

        // 设置表头样式
        JTableHeader header = table.getTableHeader();
        header.setFont(new  Font("微软雅黑", Font.BOLD, 14));
        header.setBackground(new  Color(230, 230, 230));
        header.setReorderingAllowed(false);

        // 设置表格样式
        table.setGridColor(new  Color(220, 220, 220));
        table.setShowGrid(true);
        table.setIntercellSpacing(new  Dimension(1, 1));
        table.setFont(new  Font("微软雅黑", Font.PLAIN, 13));

        return table;
    }

    // 创建带标题的边框
    private Border createTitledBorder(String title) {
        TitledBorder border = BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(new  Color(200, 200, 200)),
                title,
                TitledBorder.LEFT,
                TitledBorder.TOP,
                new Font("微软雅黑", Font.BOLD, 14),
                new Color(70, 130, 180)
        );
        border.setTitlePosition(TitledBorder.TOP);
        return border;
    }

    // 创建工具栏按钮的统一样式（优化文本显示）
    private JButton createToolbarButton(String text, String iconType) {
        JButton button = new JButton(text);
        button.setActionCommand(iconType);
        button.setFocusPainted(false);
        button.setBackground(new  Color(70, 130, 180)); // 钢蓝色背景
        button.setForeground(Color.WHITE);
        button.setFont(new  Font("微软雅黑", Font.BOLD, 13)); // 减小字体大小
        button.setMargin(new  Insets(6, 12, 6, 12)); // 优化内边距
        button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        // 添加图标（如果有）
        ImageIcon icon = getIconForType(iconType);
        if (icon != null) {
            button.setIcon(icon);
            button.setHorizontalTextPosition(SwingConstants.LEFT);  // 文本在图标右侧
            button.setIconTextGap(8);  // 图标和文本间距
        }

        // 确保按钮有足够空间显示文本
        Dimension preferredSize = button.getPreferredSize();
        button.setPreferredSize(new  Dimension(preferredSize.width  + 20, preferredSize.height));

        return button;
    }
    // 获取按钮图标（根据实际资源调整）
    private ImageIcon getIconForType(String type) {
        // 此处应替换为实际图标路径
        // 返回null表示无图标，仅显示文本
        return null;
    }
    // 添加示例数据
    private void loadData() {
        try {
            List<CompVO> list =  compDao.query(new CompVO());
            if(list != null){
                for(CompVO compVO : list){
                    compTableModel.addRow(new  Object[]{compVO.getId(), compVO.getCode(), compVO.getName()});
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    // 对话框打开方法
    private void openCreateCompDialog(ActionEvent e) {
        CreateCompDialog dialog = new CreateCompDialog();
        // 添加窗口关闭监听实现自动刷新
        dialog.addWindowListener(new  WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                refreshCompTable();
            }
        });
        dialog.setVisible(true);
    }
    private void openCreateEntityDialog(ActionEvent e) {
        if(StringUtils.isEmpty(selectedCompId)){
            showHintDialog("提示", "请选择业务组件！");
            return;
        }

        CreateEntityDialog dialog = new CreateEntityDialog();
        dialog.setData(
                "",  // id
                selectedCompId,  // compid
                "",  // code
                "",  // name
                false,  // primary
                false,   // archive
                "",     //clazzname
                ""      //dbname
        );

        dialog.addWindowListener(new  WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                refreshEntityTable(selectedCompId);
            }
        });
        dialog.setVisible(true);
    }
    private void openCreateFieldDialog(ActionEvent e) {
        if(StringUtils.isEmpty(selectedEntityId)){
            showHintDialog("提示", "请选择实体！");
            return;
        }
        CreateFieldDialog dialog = new CreateFieldDialog();
        dialog.setData(
                "",  // id
                selectedCompId,  // compid
                selectedEntityId,  // entityid
                "",  // parentcode
                false,  // primary
                "",  // code
                "",  // name
                "",  // type
                "",
                null,
                null,
                "",  // doctype
                ""   // enumtype
        );

        dialog.addWindowListener(new  WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                refreshFieldTable(selectedCompId, selectedEntityId);
            }
        });
        dialog.setVisible(true);
    }
    @Override
    public String getDefaultTile() {
        return "实体设计器";
    }
    // 对话框实现优化
    static class CreateCompDialog extends JDialog {
        private boolean isEditMode = false;
        private JTextField txtCompId;
        private JTextField txtCompcode;
        private JTextField txtCompname;
        public CreateCompDialog() {
            setTitle("创建业务组件");
            setSize(450, 220);
            setLocationRelativeTo(null);
            setModal(true);
            initUI();
        }
        private void initUI() {
            JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
            mainPanel.setBorder(BorderFactory.createEmptyBorder(15,  15, 15, 15));
            txtCompId = new JTextField(20);
            txtCompId.setVisible(false);
            JPanel formPanel = new JPanel(new GridLayout(2, 2, 10, 15));
            formPanel.add(new  JLabel("业务组件编码:"));
            formPanel.add(txtCompcode = new  JTextField(20));
            formPanel.add(new  JLabel("业务组件名称:"));
            formPanel.add(txtCompname = new  JTextField(20));

            JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
            JButton btnSubmit = new JButton("提交");
            btnSubmit.setBackground(new  Color(34, 139, 34)); // 森林绿
            btnSubmit.setForeground(Color.WHITE);
            btnSubmit.setPreferredSize(new  Dimension(100, 30));
            btnSubmit.addActionListener(this::submit);
            buttonPanel.add(btnSubmit);

            mainPanel.add(formPanel,  BorderLayout.CENTER);
            mainPanel.add(buttonPanel,  BorderLayout.SOUTH);

            add(mainPanel);
        }

        private void submit(ActionEvent e) {

            CompVO compVO = new CompVO();
            compVO.setId(txtCompId.getText().trim());
            compVO.setCode(txtCompcode.getText().trim());
            compVO.setName(txtCompname.getText().trim());

            try {
                compDao.save(compVO);
                JOptionPane.showMessageDialog(this,(isEditMode ? "更新成功" : "创建成功") ,"操作成功", JOptionPane.INFORMATION_MESSAGE);
                dispose(); // 关闭对话框
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this,(isEditMode ? "更新失败" : "创建失败") + ex.getMessage(),"失败", JOptionPane.ERROR_MESSAGE);
                throw new RuntimeException(ex);
            }
        }

        // 新增方法：设置编辑模式
        public void setEditMode(boolean editMode) {
            isEditMode = editMode;
            setTitle(editMode ? "修改业务组件" : "创建业务组件");
        }

        public void setData(String id, String code, String name) {
            txtCompId.setText(id);
            txtCompcode.setText(code);
            txtCompname.setText(name);
        }
    }

    // 创建实体对话框实现
    static class CreateEntityDialog extends JDialog {
        private JTextField txtEntityCode;
        private JTextField txtEntityName;
        private JCheckBox chkArchive;
        private JCheckBox chkPrimaryKey;
        private JTextField txtClazzname;
        private JTextField txtDbname;
        private boolean isEditMode = false;
        private JTextField txtId = new JTextField();
        private JTextField txtCompId = new JTextField();
        public CreateEntityDialog() {
            setTitle("创建实体");
            setSize(500, 400);
            setLocationRelativeTo(null);
            setModal(true);
            initUI();
        }
        private void initUI() {
            // 主面板使用BorderLayout
            JPanel mainPanel = new JPanel(new BorderLayout(10, 15));
            mainPanel.setBorder(BorderFactory.createEmptyBorder(15,  20, 15, 20));

            // 表单面板
            JPanel formPanel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets  = new Insets(8, 8, 8, 8);
            gbc.anchor  = GridBagConstraints.WEST;
            gbc.fill  = GridBagConstraints.HORIZONTAL;

            // --- 隐藏字段：所属业务组件（带默认值）---
            txtId.setVisible(false);
            txtCompId.setVisible(false);
            formPanel.add(txtId);
            formPanel.add(txtCompId);

            // === 第一行：实体编码 ===
            gbc.gridx  = 0;
            gbc.gridy  = 0;
            formPanel.add(new  JLabel("实体编码:"), gbc);

            gbc.gridx  = 1;
            gbc.weightx  = 1.0;
            txtEntityCode = new JTextField(20);
            txtEntityCode.setFont(new  Font("微软雅黑", Font.PLAIN, 13));
            formPanel.add(txtEntityCode,  gbc);

            // === 第二行：实体名称 ===
            gbc.gridx  = 0;
            gbc.gridy  = 1;
            formPanel.add(new  JLabel("实体名称:"), gbc);

            gbc.gridx  = 1;
            txtEntityName = new JTextField(20);
            txtEntityName.setFont(new  Font("微软雅黑", Font.PLAIN, 13));
            formPanel.add(txtEntityName,  gbc);

            // === 第三行：是否主实体（新增）===
            gbc.gridx  = 0;
            gbc.gridy  = 2;
            formPanel.add(new  JLabel("是否主实体:"), gbc);

            gbc.gridx  = 1;
            chkPrimaryKey = new JCheckBox("是");
            chkPrimaryKey.setFont(new  Font("微软雅黑", Font.PLAIN, 13));
            chkPrimaryKey.setBackground(null);  // 透明背景
            formPanel.add(chkPrimaryKey,  gbc);

            // === 第四行：是否档案（新增）===
            gbc.gridx  = 0;
            gbc.gridy  = 3;
            formPanel.add(new  JLabel("是否档案:"), gbc);

            gbc.gridx  = 1;
            chkArchive = new JCheckBox("是");
            chkArchive.setFont(new  Font("微软雅黑", Font.PLAIN, 13));
            chkArchive.setBackground(null);  // 透明背景
            formPanel.add(chkArchive,  gbc);

            // === 第五行：实体类 ===
            gbc.gridx  = 0;
            gbc.gridy  = 4;
            formPanel.add(new  JLabel("实体类:"), gbc);

            gbc.gridx  = 1;
            txtClazzname = new JTextField(20);
            txtClazzname.setFont(new  Font("微软雅黑", Font.PLAIN, 13));
            formPanel.add(txtClazzname,  gbc);

            // === 第六行：物理表 ===
            gbc.gridx  = 0;
            gbc.gridy  = 5;
            formPanel.add(new  JLabel("物理表:"), gbc);

            gbc.gridx  = 1;
            txtDbname = new JTextField(20);
            txtDbname.setFont(new  Font("微软雅黑", Font.PLAIN, 13));
            formPanel.add(txtDbname,  gbc);

            mainPanel.add(formPanel,  BorderLayout.CENTER);

            // 按钮面板
            JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 15, 10));

            JButton btnCancel = new JButton("取消");
            btnCancel.setBackground(new  Color(220, 220, 220));
            btnCancel.setPreferredSize(new  Dimension(90, 32));
            btnCancel.addActionListener(e  -> dispose());

            JButton btnSubmit = new JButton("提交");
            btnSubmit.setBackground(new  Color(34, 139, 34)); // 森林绿
            btnSubmit.setForeground(Color.WHITE);
            btnSubmit.setPreferredSize(new  Dimension(90, 32));
            btnSubmit.addActionListener(this::submit);

            buttonPanel.add(btnCancel);
            buttonPanel.add(btnSubmit);

            mainPanel.add(buttonPanel,  BorderLayout.SOUTH);

            add(mainPanel);
        }
        private void submit(ActionEvent e) {
            String entityCode = txtEntityCode.getText().trim();
            String entityName = txtEntityName.getText().trim();
            String clazzname = txtClazzname.getText().trim();
            String dbname = txtDbname.getText().trim();

            if (entityCode.isEmpty()  || entityName.isEmpty() || clazzname.isEmpty() || dbname.isEmpty())  {
                JOptionPane.showMessageDialog(this,
                        "实体编码和名称、实体类、物理表不能为空",
                        "输入错误", JOptionPane.WARNING_MESSAGE);
                return;
            }

            EntityVO entityVO = new EntityVO();
            entityVO.setId(txtId.getText().trim());
            entityVO.setCompId(txtCompId.getText().trim());
            entityVO.setCode(entityCode);
            entityVO.setName(entityName);
            entityVO.setIsMain(chkPrimaryKey.isSelected() ? "Y" : "N");
            entityVO.setIsDoc(chkArchive.isSelected() ? "Y" : "N");
            entityVO.setClazzname(clazzname);
            entityVO.setDbname(dbname);

            try {
                compDao.save(entityVO);
                JOptionPane.showMessageDialog(this,
                        (isEditMode ? "更新" : "创建")+"成功!\n实体编码: " + entityCode,
                        "操作成功", JOptionPane.INFORMATION_MESSAGE);
                dispose();
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this,
                        ex.getMessage(),
                        (isEditMode ? "更新失败" : "创建失败")+ex.getMessage(),
                        JOptionPane.ERROR_MESSAGE);
            }
        }

        // 新增方法：设置编辑模式
        public void setEditMode(boolean editMode) {
            isEditMode = editMode;
            setTitle(editMode ? "修改实体" : "创建实体");
        }
        // 新增方法：设置对话框数据
        public void setData(String id, String compId,
                            String code, String name,
                            boolean primary, boolean archive, String clazzname, String dbname) {
            txtId.setText(id);
            txtCompId.setText(compId);
            txtEntityCode.setText(code);
            txtEntityName.setText(name);
            chkPrimaryKey.setSelected(primary);
            chkArchive.setSelected(archive);
            txtClazzname.setText(clazzname);
            txtDbname.setText(dbname);
        }
    }
    // 创建字段对话框实现
    static class CreateFieldDialog extends JDialog {
        private boolean isEditMode = false;
        // 隐藏字段（带默认值）
        private JTextField txtId = new JTextField("AUTO_GEN");
        private JTextField txtCompId = new JTextField("COMP_SALE");
        private JTextField txtEntityId = new JTextField("ORDER_MAIN");
        private JTextField txtParentCode = new JTextField("ROOT_FIELD");
        private JTextField txtDoc = new JTextField("");
        private JTextField txtEnmu = new JTextField("");

        // 原有字段
        private JTextField txtFieldCode;
        private JTextField txtFieldName;
        private JTextField txtDbtype;
        private JTextField txtDblength;
        private JTextField txtDbjd;
        private JComboBox<String> cmbFieldType;
        private JCheckBox chkPrimaryKey;

        public CreateFieldDialog() {
            setTitle("创建字段");
            setSize(600, 550);
            setLocationRelativeTo(null);
            setModal(true);
            initUI();
        }

        private void initUI() {
            // 设置隐藏字段
            txtId.setVisible(false);
            txtCompId.setVisible(false);
            txtEntityId.setVisible(false);
            txtParentCode.setVisible(false);

            // 主面板布局
            JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
            mainPanel.setBorder(BorderFactory.createEmptyBorder(15,  20, 15, 20));

            // 表单面板
            JPanel formPanel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets  = new Insets(8, 8, 8, 8);
            gbc.anchor  = GridBagConstraints.WEST;
            gbc.fill  = GridBagConstraints.HORIZONTAL;

            // === 第一行：字段编码 ===
            gbc.gridx  = 0;
            gbc.gridy  = 0;
            formPanel.add(new  JLabel("字段编码:"), gbc);

            gbc.gridx  = 1;
            gbc.weightx  = 1.0;
            txtFieldCode = new JTextField(20);
            txtFieldCode.setFont(new  Font("微软雅黑", Font.PLAIN, 13));
            formPanel.add(txtFieldCode,  gbc);

            // === 第二行：字段名称 ===
            gbc.gridx  = 0;
            gbc.gridy  = 1;
            formPanel.add(new  JLabel("字段名称:"), gbc);

            gbc.gridx  = 1;
            txtFieldName = new JTextField(20);
            txtFieldName.setFont(new  Font("微软雅黑", Font.PLAIN, 13));
            formPanel.add(txtFieldName,  gbc);

            // === 第三行：字段类型 ===
            gbc.gridx  = 0;
            gbc.gridy  = 2;
            formPanel.add(new  JLabel("字段类型:"), gbc);

            gbc.gridx  = 1;
            cmbFieldType = new JComboBox<>(new String[]{"String", "Boolean", "Integer", "Double", "Date", "Doc", "Enum"});
            cmbFieldType.setFont(new  Font("微软雅黑", Font.PLAIN, 13));
            formPanel.add(cmbFieldType,  gbc);

            // === 第四行：是否主键 ===
            gbc.gridx  = 0;
            gbc.gridy  = 3;
            formPanel.add(new  JLabel("主键标识:"), gbc);

            gbc.gridx  = 1;
            chkPrimaryKey = new JCheckBox("设为主键字段");
            chkPrimaryKey.setFont(new  Font("微软雅黑", Font.PLAIN, 13));
            formPanel.add(chkPrimaryKey,  gbc);

            // === 第五行：数据类型 ===
            gbc.gridx  = 0;
            gbc.gridy  = 4;
            formPanel.add(new  JLabel("数据类型:"), gbc);

            gbc.gridx  = 1;
            txtDbtype = new JTextField(20);
            txtDbtype.setFont(new  Font("微软雅黑", Font.PLAIN, 13));
            formPanel.add(txtDbtype,  gbc);

            // === 第六行：字段长度 ===
            gbc.gridx  = 0;
            gbc.gridy  = 5;
            formPanel.add(new  JLabel("字段长度:"), gbc);

            gbc.gridx  = 1;
            txtDblength = new JTextField(20);
            txtDblength.setFont(new  Font("微软雅黑", Font.PLAIN, 13));
            formPanel.add(txtDblength,  gbc);

            // === 第七行：字段精度 ===
            gbc.gridx  = 0;
            gbc.gridy  = 6;
            formPanel.add(new  JLabel("字段精度:"), gbc);

            gbc.gridx  = 1;
            txtDbjd = new JTextField(20);
            txtDbjd.setFont(new  Font("微软雅黑", Font.PLAIN, 13));
            formPanel.add(txtDbjd,  gbc);

            // === 第八行：参照类型 ===
            gbc.gridx  = 0;
            gbc.gridy  = 7;
            formPanel.add(new  JLabel("参照类型:"), gbc);

            gbc.gridx  = 1;
            txtDoc = new JTextField(20);
            txtDoc.setFont(new  Font("微软雅黑", Font.PLAIN, 13));
            formPanel.add(txtDoc,  gbc);

            // === 第九行：枚举类型 ===
            gbc.gridx  = 0;
            gbc.gridy  = 8;
            formPanel.add(new  JLabel("枚举类型:"), gbc);

            gbc.gridx  = 1;
            txtEnmu = new JTextField(20);
            txtEnmu.setFont(new  Font("微软雅黑", Font.PLAIN, 13));
            formPanel.add(txtEnmu,  gbc);

            // 添加隐藏字段
            formPanel.add(txtId);
            formPanel.add(txtCompId);
            formPanel.add(txtEntityId);
            formPanel.add(txtParentCode);

            mainPanel.add(formPanel,  BorderLayout.CENTER);

            // 按钮面板
            JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 15, 10));

            JButton btnCancel = new JButton("取消");
            btnCancel.setBackground(new  Color(220, 220, 220));
            btnCancel.setPreferredSize(new  Dimension(90, 32));
            btnCancel.addActionListener(e  -> dispose());

            JButton btnSubmit = new JButton("提交");
            btnSubmit.setBackground(new  Color(34, 139, 34));
            btnSubmit.setForeground(Color.WHITE);
            btnSubmit.setPreferredSize(new  Dimension(90, 32));
            btnSubmit.addActionListener(this::submit);

            buttonPanel.add(btnCancel);
            buttonPanel.add(btnSubmit);

            mainPanel.add(buttonPanel,  BorderLayout.SOUTH);

            add(mainPanel);
        }

        // 新增方法：设置编辑模式
        public void setEditMode(boolean editMode) {
            isEditMode = editMode;
            setTitle(editMode ? "修改字段" : "创建字段");
        }

        // 新增方法：设置对话框数据
        public void setData(String id, String compId, String entityId,
                            String parentCode, boolean primary,
                            String code, String name, String type, String dbtype, Integer dblength, Integer dbjd,
                            String docType, String enumType) {
            txtId.setText(id);
            txtCompId.setText(compId);
            txtEntityId.setText(entityId);
            txtParentCode.setText(parentCode);
            chkPrimaryKey.setSelected(primary);
            txtFieldCode.setText(code);
            txtFieldName.setText(name);
            cmbFieldType.setSelectedItem(type);
            txtDoc.setText(docType);
            txtEnmu.setText(enumType);
            txtDbtype.setText(dbtype);
            txtDblength.setText(dblength == null ? "" : String.valueOf(dblength));
            txtDbjd.setText(dbjd == null ? "" : String.valueOf(dbjd));
        }

        private void submit(ActionEvent e) {
            AttributeVO attributeVO = new AttributeVO();
            attributeVO.setId(txtId.getText().trim());
            attributeVO.setCompId(txtCompId.getText().trim());
            attributeVO.setEntityId(txtEntityId.getText().trim());
            attributeVO.setParentCode(txtParentCode.getText().trim());
            attributeVO.setIsPriKey(chkPrimaryKey.isSelected() ? "Y" : "N");
            attributeVO.setCode(txtFieldCode.getText().trim());
            attributeVO.setName(txtFieldName.getText().trim());
            attributeVO.setType(cmbFieldType.getSelectedItem().toString());
            attributeVO.setDocCompId(txtDoc.getText().trim());
            attributeVO.setEnmu(txtEnmu.getText().trim());
            attributeVO.setDbtype(txtDbtype.getText().trim());
            attributeVO.setDblength(txtDblength.getText().trim().length() == 0 ? null : Integer.parseInt(txtDblength.getText().trim()));
            attributeVO.setDbjd(txtDbjd.getText().trim().length() == 0 ? null : Integer.parseInt(txtDbjd.getText().trim()));

            try {
                compDao.save(attributeVO);
                JOptionPane.showMessageDialog(this,(isEditMode ? "更新" : "创建")+
                        "成功!\n字段编码: " + attributeVO.getCode(),
                        "操作成功", JOptionPane.INFORMATION_MESSAGE);
                dispose();
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this,
                        ex.getMessage(),
                        (isEditMode ? "更新失败" : "创建失败")+ex.getMessage(),
                        JOptionPane.ERROR_MESSAGE);
                ex.printStackTrace();
            }
        }
    }
}